class Ability
  include CanCan::Ability
  def initialize(user)
    # Define abilities for the passed in user here. For example:
    #
    #   user ||= User.new # guest user (not logged in)
    #   if user.admin?
    #     can :manage, :all
    #   else
    #     can :read, :all
    #   end
    #
    # The first argument to `can` is the action you are giving the user permission to do.
    # If you pass :manage it will apply to every action. Other common actions here are
    # :read, :create, :update and :destroy.
    #
    # The second argument is the resource the user can perform the action on. If you pass
    # :all it will apply to every resource. Otherwise pass a Ruby class of the resource.
    #
    # The third argument is an optional hash of conditions to further filter the objects.
    # For example, here the user can only update published articles.
    #
    #   can :update, Article, :published => true
    #
    # See the wiki for details: https://github.com/ryanb/cancan/wiki/Defining-Abilities

    #Rails.logger.debug 'Ability Group : '+user.group.name+'['+user.group.id.to_s+']'
    @authentications = Authentication.find :all , :conditions => "group_id = "+user.group.id.to_s
    #Rails.logger.debug 'Ability authentication : '+@authentications.to_s

    @authentications.each do |authentication|
      #Rails.logger.debug 'Permission : '+authentication.permission.code+'/'+User.permission_code.to_s
      #if authentication.permission.code == User.permission_code.to_s
      model_class = Object.const_get(authentication.permission.model.name)
      validate_authentication(authentication,model_class)
      #end
    end

  end

  private
  def validate_authentication(authentication , model)
    if authentication.can_create
      can :create, model
    end
    if authentication.can_read
      can :read, model
    end
    if authentication.can_update
      can :update, model
    end
    if authentication.can_destroy
      can :destroy, model
    end
  end

end
